package com.stylefeng.guns.modular.clm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.clm.AdminConstant;
import com.stylefeng.guns.core.util.clm.AdminTools;
import com.stylefeng.guns.core.util.clm.LiveUploadImg;
import com.stylefeng.guns.core.util.clm.RedisService;
import com.stylefeng.guns.modular.clm.service.IClmColumnRoomService;
import com.stylefeng.guns.modular.clm.service.IClmRoomService;
import com.stylefeng.guns.modular.clm.service.ITeacherRoomService;
import com.stylefeng.guns.modular.clm.service.ITeacherService;
import com.stylefeng.guns.modular.system.model.ClmAreaEntity;
import com.stylefeng.guns.modular.system.model.ClmColumnRoom;
import com.stylefeng.guns.modular.system.model.ClmRoom;
import com.stylefeng.guns.modular.system.model.ClmSubjectEntity;
import com.stylefeng.guns.modular.system.model.ClmUserEntity;
import com.stylefeng.guns.modular.system.model.Teacher;
import com.stylefeng.guns.modular.system.model.TeacherRoom;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2018-05-28 11:26:27
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseController {

	private final static Logger logger = LoggerFactory.getLogger(TeacherController.class);
    private String PREFIX = "/clm/teacher/";

    @Autowired
	private RedisService redisService ;
    
    @Autowired
    private ITeacherService teacherService;
    
    @Autowired
    private IClmRoomService clmRoomService;
    
    @Autowired
    private ITeacherRoomService teacherRoomService;
    
    @Autowired
    private IClmColumnRoomService clmColumnRoomService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index(Model model) {
    	//获取省列表
		try {
			List<ClmAreaEntity> l_province = null;
    		if(redisService.exists("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID)){
    			l_province = (List<ClmAreaEntity>) redisService.get("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID);
    			if(l_province !=null && l_province.size()>0){
    				model.addAttribute("provinceList",l_province);
    			}else{
    				String provinceList=AdminTools.findProvinceList("",AdminConstant.DEFAULT_SITEID);
    				if(StringUtils.isNotBlank(provinceList)){
    					JSONObject jsonObj=JSON.parseObject(provinceList);
    					l_province=JSON.parseArray(jsonObj.get("message").toString(), ClmAreaEntity.class);
    					model.addAttribute("provinceList",l_province);
    					redisService.set("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID, l_province);
    				}
    			}
    			
    		}else{
				String provinceList=AdminTools.findProvinceList("",AdminConstant.DEFAULT_SITEID);
				if(StringUtils.isNotBlank(provinceList)){
					JSONObject jsonObj=JSON.parseObject(provinceList);
					l_province=JSON.parseArray(jsonObj.get("message").toString(), ClmAreaEntity.class);
					model.addAttribute("provinceList",l_province);
					redisService.set("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID, l_province);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        return PREFIX + "teacher.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/teacher_add")
    public String teacherAdd() {
        return PREFIX + "teacher_add.html";
    }
    
    /**
     * 跳转到教师课程添加页
     */
    @RequestMapping("/teacherRoom_add")
    public String teacherRoomAdd(Model model) {
    	model.addAttribute("teacherId", this.getPara("teacherId"));
        return PREFIX + "teacherRoom_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/teacher_update/{id}")
    public String teacherUpdate(@PathVariable Integer id, Model model) {
        Teacher teacher = teacherService.selectById(id);
        List<ClmSubjectEntity> l_clmSubjectEntity=new ArrayList<ClmSubjectEntity>();
      //获取老师信息
		try {
			String user = AdminTools.getTeacherBySiteIdTeacherId(teacher.getSiteId(), teacher.getTeacherId());
			if(user !=null ){
				JSONObject jsonObj=JSON.parseObject(user);
				ClmUserEntity clmUser=jsonObj.parseObject(jsonObj.get("clmUserEntity").toString(), ClmUserEntity.class);
				//老师信息
				model.addAttribute("clmUser",clmUser);
				logger.info("clmUser===="+teacher.toString());
				
			}
			
			//教师科目信息
			
			String subjects = AdminTools.getSubjectByTeacherId(teacher.getTeacherId(), teacher.getSiteId());
			if(StringUtils.isNotBlank(subjects)){
				JSONObject jsonObj=JSON.parseObject(subjects);
				if(jsonObj.get("l_clmSubjectEntity")!=null){
					l_clmSubjectEntity = JSON.parseArray(jsonObj.get("l_clmSubjectEntity").toString(), ClmSubjectEntity.class);
				}
				
				//老师科目信息
				logger.info("l_clmSubjectEntity===="+l_clmSubjectEntity.toString());
			}
		} catch (Exception e) {
			logger.info("teacherUpdate siteid==="+teacher.getSiteId()+" teacherId==="+teacher.getTeacherId()+"获取老师信息失败");
			e.printStackTrace();
		}
		
		model.addAttribute("l_clmSubjectEntity",l_clmSubjectEntity);
		//名师表名师信息
        model.addAttribute("item",teacher);
        LogObjectHolder.me().set(teacher);
        return PREFIX + "teacher_edit.html";
    }
    
    

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Teacher teacher) {
    	EntityWrapper<Teacher> entityWrapper=new EntityWrapper<Teacher>();
    	Wrapper<Teacher> wrapper=null ;
    	logger.info("==================="+teacher.toString());
    	if(StringUtils.isNotBlank(teacher.getTeacherName())){
    		wrapper=entityWrapper.like("teacher_name", teacher.getTeacherName().trim());
    	}
    	if(StringUtils.isNotBlank(teacher.getTeacherId())){
    		wrapper=entityWrapper.eq("teacher_id", teacher.getTeacherId());
    	}
    	
    	if(StringUtils.isNotBlank(teacher.getAccountId())){
    		wrapper=entityWrapper.eq("account_id", teacher.getAccountId());
    	}
    	
    	if(StringUtils.isNotBlank(teacher.getOrgProvinceCode())){
    		wrapper=entityWrapper.eq("org_province_code", teacher.getOrgProvinceCode());
    	}
    	if(StringUtils.isNotBlank(teacher.getOrgCityCode())){
    		wrapper=entityWrapper.eq("org_city_code", teacher.getOrgCityCode());
    	}
    	if(StringUtils.isNotBlank(teacher.getOrgAreaCode())){
    		wrapper=entityWrapper.eq("org_area_code", teacher.getOrgAreaCode());
    	}
    	if(StringUtils.isNotBlank(teacher.getSchoolId())){
    		wrapper=entityWrapper.eq("school_id", teacher.getSchoolId());
    	}
    	
    	entityWrapper.eq("site_id", AdminConstant.DEFAULT_SITEID);
    	entityWrapper.eq("be_delete", "0");
    	wrapper=entityWrapper.orderBy("be_top", false).orderBy("update_time", false);
        return teacherService.selectList(wrapper);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Teacher teacher) {
    	EntityWrapper<Teacher> entityWrapper=new EntityWrapper<Teacher>();
    	Wrapper<Teacher> wrapper=null ;
    	//教师区域ID
    	String siteId=AdminConstant.DEFAULT_SITEID;
    	logger.info("==================="+teacher.toString());
    	if(StringUtils.isNotBlank(teacher.getSiteId())){
    		wrapper=entityWrapper.eq("site_id", teacher.getSiteId());
    	}
    	if(StringUtils.isNotBlank(teacher.getTeacherId())){
    		wrapper=entityWrapper.eq("teacher_id", teacher.getTeacherId());
    	}
    	
    	wrapper=entityWrapper.eq("be_delete", "0");
    	int i=teacherService.selectCount(wrapper);
    	if(i>0){
    		SUCCESS_TIP.setMessage("老师已经在名师中！");
    		return SUCCESS_TIP;
    	}else{
    		//获取老师信息
    		
			try {
				String user = AdminTools.getTeacherBySiteIdTeacherId(siteId, teacher.getTeacherId());
				if(user !=null ){
					JSONObject jsonObj=JSON.parseObject(user);
					ClmUserEntity clmUser=jsonObj.parseObject(jsonObj.get("clmUserEntity").toString(), ClmUserEntity.class);
					logger.info("clmUser===="+teacher.toString());
					teacher.setSiteId(siteId);
					teacher.setTeacherName(clmUser.getName());
					teacher.setOrgProvinceCode(clmUser.getOrgProvinceCode());
					teacher.setOrgProvinceName(clmUser.getOrgProvinceName());
					teacher.setOrgCityCode(clmUser.getOrgCityCode());
					teacher.setOrgCityName(clmUser.getOrgCityName());
					teacher.setOrgAreaCode(clmUser.getOrgAreaCode());
					teacher.setOrgAreaName(clmUser.getOrgAreaName());
					teacher.setSchoolId(clmUser.getSchoolId());
					teacher.setSchoolName(clmUser.getSchoolName());
					teacher.setAccountId(clmUser.getAccountID());
					Date date_now=new Date();
					teacher.setCreateTime(date_now);
				}
			} catch (Exception e) {
				logger.info("siteid==="+siteId+" teacherId==="+teacher.getTeacherId()+"获取老师信息失败");
				SUCCESS_TIP.setMessage("获取老师信息失败");
				e.printStackTrace();
				return SUCCESS_TIP;
			}
			
    	}
        teacherService.insert(teacher);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer id,@RequestParam String teacherId) {
    	Map<String, Object> columnMap=new HashMap<String, Object>();
    	columnMap.put("teacher_id", teacherId);
    	teacherRoomService.deleteByMap(columnMap);
        teacherService.deleteById(id);
        return SUCCESS_TIP;
    }
    
    /**
     * 上下架
     */
    @RequestMapping(value = "/downOrUp")
    @ResponseBody
    public Object downOrUp(@RequestParam Integer id) {
    	Teacher  teacher=teacherService.selectById(id);
    	if("0".equals(teacher.getStatus())){
    		teacher.setStatus("1");//状态 1-开启 0-禁用
    	}else{
    		teacher.setStatus("0");//状态 1-开启 0-禁用
    	}
    	Date date_now=new Date();
    	teacher.setUpdateTime(date_now);
    	teacherService.updateById(teacher);
        return SUCCESS_TIP;
    }
    
    /**
     * 置顶或取消置顶
     */
    @RequestMapping(value = "/topOrNo")
    @ResponseBody
    public Object topOrNo(@RequestParam Integer id) {
    	Teacher  teacher=teacherService.selectById(id);
    	if("0".equals(teacher.getBeTop())){
    		teacher.setBeTop("1");//置顶 0-否 1-是
    	}else{
    		teacher.setBeTop("0");//置顶 0-否 1-是
    	}
    	Date date_now=new Date();
    	teacher.setUpdateTime(date_now);
    	teacherService.updateById(teacher);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Teacher teacher) {
    	String imageUrl=this.getPara("PCavatar");
    	String phoneUrl=this.getPara("H5avatar");
    	
    	String teacherDesc=this.getPara("teacherDesc");
    	
    	teacher=teacherService.selectById(teacher.getId());
    	if(StringUtils.isNotBlank(imageUrl)){
    		teacher.setImageUrl(LiveUploadImg.upImg(imageUrl));
    	}
    	if(StringUtils.isNotBlank(phoneUrl)){
    		teacher.setPhoneUrl(LiveUploadImg.upImg(phoneUrl));
    	}
    	teacher.setTeacherDesc(teacherDesc);
    	
        teacherService.updateById(teacher);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{teacherId}")
    @ResponseBody
    public Object detail(@PathVariable("teacherId") Integer teacherId) {
        return teacherService.selectById(teacherId);
    }    
    
    /**
     * 获取名师
     */
    @RequestMapping(value = "/getTeacher")
    @ResponseBody
    public Object getTeacher() {
    	//教师ID
    	String accountId=this.getPara("accountId");
    	//教师区域ID
    	String siteId=AdminConstant.DEFAULT_SITEID;
    	ClmUserEntity teacher = null;
		try {
			String user = AdminTools.getTeacherBySiteIdAccountId(siteId, accountId);
			if(user !=null ){
				JSONObject jsonObj=JSON.parseObject(user);
				teacher=jsonObj.parseObject(jsonObj.get("clmUserEntity").toString(), ClmUserEntity.class);
				logger.info("teacher="+teacher.toString());
			}
			
			
		} catch (Exception e) {
			logger.info("获取用户失败或用户不存在，请核对站点和用户ID！");
			e.printStackTrace();
		}
		return teacher;
    }
    
    
    /**
     * 获取名师课程
     */
    @RequestMapping(value = "/getRoom")
    @ResponseBody
    public Object getRoom() {
    	//课程ID
    	String number=this.getPara("number");
    	//课程名称
    	String roomSubject=this.getPara("roomSubject");
    	//老师ID
    	String teacherId=this.getPara("teacherId");
    	List<ClmRoom> l_clmRoom=null;
		try {
			EntityWrapper<ClmRoom> entityWrapper=new EntityWrapper<ClmRoom>();
	    	Wrapper<ClmRoom> wrapper=null ;
	    	if(StringUtils.isNotBlank(number)){
	    		entityWrapper.eq("number_", number);
	    	}
	    	if(StringUtils.isNotBlank(roomSubject)){
	    		entityWrapper.like("subject_", roomSubject);
	    	}
	    	if(StringUtils.isNotBlank(teacherId)){
	    		entityWrapper.eq("teacher_id", teacherId);
	    	}
	    	
	    	wrapper=entityWrapper.eq("be_deleted", 0);
	        l_clmRoom = clmRoomService.selectList(wrapper);
		} catch (Exception e) {
			logger.info("getRoom "+e.getMessage());
			e.printStackTrace();
		}
		return l_clmRoom;
    }
    
    
    /**
     * 新增
     */
    @RequestMapping(value = "/teacherRoomAdd")
    @ResponseBody
    public Object teacherRoomAdd() {
    	String teacherId=this.getPara("teacherId");
    	String roomId=this.getPara("roomId");
    	//String siteId=AdminConstant.DEFAULT_SITEID;
    	
    	EntityWrapper<TeacherRoom> entityWrapper=new EntityWrapper<TeacherRoom>();
    	Wrapper<TeacherRoom> wrapper=null ;
    	/*if(StringUtils.isNotBlank(siteId)){
    		wrapper=entityWrapper.eq("site_id", siteId);
    	}*/
    	if(StringUtils.isNotBlank(teacherId)){
    		wrapper=entityWrapper.eq("teacher_id", teacherId);
    	}
    	if(StringUtils.isNotBlank(roomId)){
    		wrapper=entityWrapper.eq("room_id", roomId);
    	}
    	
    	wrapper=entityWrapper.eq("be_delete", "0");
    	int i=teacherRoomService.selectCount(wrapper);
    	TeacherRoom entity= new TeacherRoom();
    	if(i>0){
    		SUCCESS_TIP.setInfo("课程已在列表中！");
    		return SUCCESS_TIP;
    	}else{
    		entity.setTeacherId(teacherId);
        	entity.setRoomId(roomId);
    	}
    	logger.info("teacherRoomAdd ==================="+entity.toString());
    	teacherRoomService.insert(entity);
    	
    	//名师栏目新增课程
    	String columnId=AdminConstant.COLUMN_MS_ID;
    	String siteId=AdminConstant.DEFAULT_SITEID;
    	
    	EntityWrapper<ClmColumnRoom> columnEntityWrapper=new EntityWrapper<ClmColumnRoom>();
    	Wrapper<ClmColumnRoom> columnWrapper=null ;
    	if(StringUtils.isNotBlank(siteId)){
    		columnWrapper=columnEntityWrapper.eq("site_id", siteId);
    	}
    	if(StringUtils.isNotBlank(columnId)){
    		columnWrapper=columnEntityWrapper.eq("column_id", columnId);
    	}
    	if(StringUtils.isNotBlank(roomId)){
    		columnWrapper=columnEntityWrapper.eq("room_id", roomId);
    	}
    	
    	columnWrapper=columnEntityWrapper.eq("is_delete", "0");
    	int j=clmColumnRoomService.selectCount(columnWrapper);
    	ClmColumnRoom ccr=new ClmColumnRoom();
    	if(j>0){
    		SUCCESS_TIP.setInfo("操作成功");
    		return SUCCESS_TIP;
    	}else{
			ccr.setColumnId(columnId);
			ccr.setSiteId(siteId);
			ccr.setRoomId(roomId);
			Date date_now=new Date();
			ccr.setCreateDate(date_now);
			clmColumnRoomService.insert(ccr);
    	}
    	
    	
    	SUCCESS_TIP.setInfo("操作成功");
        return SUCCESS_TIP;
    }
}
